import React, { useState, useEffect } from 'react';
import { Tabs, Card, Button, Alert, Spin, Tag, message } from 'antd';
import styles from './index.less';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { tomorrowNightBlue } from 'react-syntax-highlighter/dist/cjs/styles/prism';
import { useLocation } from 'umi'; // 用于获取URL参数

const { TabPane } = Tabs;

const CodeComparisonPage: React.FC = () => {
  const location = useLocation(); // 获取 location 对象
  // 从 query 中取出参数
  const { sourceUrl, optimizedUrl, reportUrl } = location.query as {
    sourceUrl: string;
    optimizedUrl: string;
    reportUrl: string;
  };
  const [sourceCode, setSourceCode] = useState('');
  const [optimizedCode, setOptimizedCode] = useState('');
  const [reportText, setReportText] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  useEffect(() => {
    const fetchData = async () => {
      try {
        // 使用URL参数加载文件
        const [sourceRes, optimizedRes, reportRes] = await Promise.all([
          fetch(sourceUrl),
          fetch(optimizedUrl),
          fetch(reportUrl),
        ]);

        // 校验响应状态
        if (!sourceRes.ok) throw new Error(`源代码失败: ${sourceRes.status}`);
        if (!optimizedRes.ok) throw new Error(`优化代码失败: ${optimizedRes.status}`);
        if (!reportRes.ok) throw new Error(`报告失败: ${reportRes.status}`);

        // 读取文本内容
        setSourceCode(await sourceRes.text());
        setOptimizedCode(await optimizedRes.text());
        setReportText(await reportRes.text());
      } catch (err) {
        setError(err instanceof Error ? err.message : '加载失败');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [sourceUrl, optimizedUrl, reportUrl]); // 依赖变化时重新请求

  // 复制逻辑
  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text).then(
      () => message.success('复制成功'),
      (err) => {
        message.error('复制失败');
        console.error(err);
      },
    );
  };

  return (
    <div className={styles['code-comparison-page']}>
      {error && (
        <Alert
          message="加载失败"
          description={error}
          type="error"
          className={styles['error-message']}
        />
      )}

      {loading ? (
        <div className={styles['loading-indicator']}>
          <Spin size="large" tip="加载中..." />
        </div>
      ) : (
        <Tabs defaultActiveKey="code">
          {/* 代码对比标签页 */}
          <TabPane tab="代码对比" key="code">
            <Card className={styles['code-card']}>
              <div className={styles['code-header']}>
                <Tag color="blue" style={{ marginRight: 8 }}>
                  源代码
                </Tag>
                <Button onClick={() => copyToClipboard(sourceCode)}>复制</Button>
              </div>
              <SyntaxHighlighter
                style={tomorrowNightBlue}
                language="cpp"
                PreTag="div"
                wrapLines
                lineNumberStyle={{ color: '#999' }}
              >
                {sourceCode}
              </SyntaxHighlighter>
            </Card>

            <Card className={styles['code-card']} style={{ marginTop: 24 }}>
              <div className={styles['code-header']}>
                <Tag color="green" style={{ marginRight: 8 }}>
                  优化代码
                </Tag>
                <Button onClick={() => copyToClipboard(optimizedCode)}>复制</Button>
              </div>
              <SyntaxHighlighter
                style={tomorrowNightBlue}
                language="cpp"
                PreTag="div"
                wrapLines
                lineNumberStyle={{ color: '#999' }}
              >
                {optimizedCode}
              </SyntaxHighlighter>
            </Card>
          </TabPane>

          {/* 优化报告标签页（纯文本展示） */}
          <TabPane tab="优化报告" key="report">
            <Card
              className={styles['report-card']}
              style={{ backgroundColor: '#e6f3ff' }} // 直接设置内联背景样式
            >
              <pre style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>{reportText}</pre>
              <div style={{ textAlign: 'right', marginTop: 16 }}>
                <Button onClick={() => copyToClipboard(reportText)}>复制报告</Button>
              </div>
            </Card>
          </TabPane>
        </Tabs>
      )}
    </div>
  );
};

export default CodeComparisonPage;
